const { Product, ProductTags, Tag, VA, Circle, Series, Op } = require('../src/models');

async function searchProducts(search) {

    let current = 1;
    let pageSize = 15;
    const offset = (current - 1) * pageSize;

    // 将搜索字符串拆分为关键字数组
    const searchTerms = search ? search.split(' ') : [];

    // 构建查询条件
    let where = {};

    if (searchTerms.length > 0) {
        const orConditions = [];

        // 在产品的 rjCode, title, translatedTitle 字段中搜索
        searchTerms.forEach(term => {
            const likeTerm = `%${term}%`;
            orConditions.push(
                { rjCode: { [Op.like]: likeTerm } },
                { title: { [Op.like]: likeTerm } },
                { translatedTitle: { [Op.like]: likeTerm } }
            );
        });

        // 在关联表的字段中搜索
        searchTerms.forEach(term => {
            const likeTerm = `%${term}%`;
            orConditions.push(
                { '$Circle.name$': { [Op.like]: likeTerm } },
                { '$Series.name$': { [Op.like]: likeTerm } },
                { '$VAs.name$': { [Op.like]: likeTerm } },
                { '$Tags.name$': { [Op.like]: likeTerm } }
            );
        });

        where = {
            [Op.or]: orConditions
        };
    }

    // 查询产品及其关联的模型
    const products = await Product.findAndCountAll({
        order: [['createdAt', 'DESC']],
        limit: pageSize,
        offset,
        where,
        include: [
            {
                model: Circle,
                attributes: ['id', 'name'],
                required: false // 左连接，包含没有关联圈子的产品
            },
            {
                model: Series,
                attributes: ['id', 'name'],
                required: false
            },
            {
                model: VA,
                attributes: ['name'],
                through: { attributes: [] }, // 多对多关系，省略中间表的字段
                required: false
            },
            {
                model: Tag,
                attributes: ['name'],
                through: { attributes: [] },
                required: false
            }
        ]
    });

    // 构建结果
    const result = products.rows.map(product => {
        // 获取关联的圈子名称
        const circleName = product.Circle ? product.Circle.name : null;

        // 获取关联的系列名称
        const seriesName = product.Series ? product.Series.name : null;

        // 获取关联的声优名称列表
        const vas = product.VAs ? product.VAs.map(va => va.name) : [];

        // 获取关联的标签名称列表
        const tags = product.Tags ? product.Tags.map(tag => tag.name) : [];

        return {
            id: product.id,
            rjCode: product.rjCode,
            title: product.translatedTitle ? product.translatedTitle : product.title,
            rating: product.rating,
            ageCategory: product.ageCategory,
            circle: circleName,
            series: seriesName,
            tags: tags,
            vas: vas,
            isVR: product.isVR,
            lang: product.lang || null,
            isSub: product.isSub
        };
    });

    const total = products.count;

    return { total, result };
}

// 调用搜索功能
searchProducts('text1 text2').then(result => {
    console.log(result);
}).catch(err => {
    console.error(err);
});
